package com.linln.admin.good.controller;

import com.linln.admin.good.domain.Category;
import com.linln.admin.good.service.CategoryService;
import com.linln.admin.good.validator.CategoryValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类管理器
 * @date 2021/04/03
 */
@Controller
@RequestMapping("/Category/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("Category:category:index")
    public String index(Model model, Category category) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains());

        // 获取数据列表
        Example<Category> example = Example.of(category, matcher);
        Page<Category> list = categoryService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/Category/category/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("Category:category:add")
    public String toAdd() {
        return "/Category/category/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("Category:category:edit")
    public String toEdit(@PathVariable("id") Category category, Model model) {
        Category pCategory = categoryService.getById(category.getPid());
        if(pCategory==null){
            pCategory = new Category();
            pCategory.setId((long) 0);
            pCategory.setTitle("顶级分类");
        }
        model.addAttribute("pCategory",pCategory);
        model.addAttribute("category", category);
        return "/Category/category/add";
    }


    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"Category:category:add", "Category:category:edit"})
    @ResponseBody
    public ResultVo save(@Validated CategoryValid valid, Category category) {
        if (category.getId() == null) {
            // 排序为空时，添加到最后
            if(category.getSort() == null){
                Integer sortMax = categoryService.getSortMax(category.getPid());
                category.setSort(sortMax !=null ? sortMax - 1 : 0);
            }
        }

        // 添加/更新全部上级序号
        if (category.getPid() != 0) {
            Category pCategory = categoryService.getById(category.getPid());
            category.setPids(pCategory.getPids() + ",[" + category.getPid() + "]");
            category.setType(pCategory.getType()+1);
        } else {
            category.setPids("[0]");
            category.setType(1);
        }

        // 将验证的数据复制给实体类
        if (category.getId() != null) {
            Category beCategory = categoryService.getById(category.getId());
            EntityBeanUtil.copyProperties(beCategory, category);
        }


        // 排序功能
        Integer sort = category.getSort();
        Long notId = category.getId() != null ? category.getId() : 0;
        List<Category> levelCategory = categoryService.getListByPid(category.getPid(), notId);
        List<Category> collect = levelCategory.stream().sorted(Comparator.comparingInt(Category::getSort)).collect(Collectors.toList());
        collect.add(sort>collect.size()?collect.size():sort,category);
        for (int i = 1; i <= collect.size(); i++) {
            collect.get(i - 1).setSort(i);
        }

        // 保存数据
        categoryService.save(collect);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("Category:category:detail")
    public String toDetail(@PathVariable("id") Category category, Model model) {
        model.addAttribute("category",category);
        return "/Category/category/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("Category:category:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (categoryService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }


    /**
     * 部门数据列表
     */
    @GetMapping("/list")
    @RequiresPermissions(value = {"good:category:index"})
    @ResponseBody
    public ResultVo list(Category category) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("title", match -> match.contains());

        // 获取部门列表
        Example<Category> example = Example.of(category, matcher);
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        List<Category> list = categoryService.getListByExample(example, sort);
        return ResultVoUtil.success(list);
    }

    
}